package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.common.Code;
import com.ruan.common.MessageConstant;
import com.ruan.common.Result;
import com.ruan.exception.BusinessException;
import com.ruan.mapper.CommonUserMapper;
import com.ruan.mapper.EmployeeMapper;
import com.ruan.pojo.CommonUser;
import com.ruan.pojo.Employee;
import com.ruan.service.CommonUserService;
import com.ruan.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
@Slf4j
@Transactional
public class CommonUserServiceImpl extends ServiceImpl<CommonUserMapper, CommonUser> implements CommonUserService {

    @Resource
    private CommonUserMapper commonUserMapper;

    @Resource
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmployeeService employeeService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private BCryptPasswordEncoder encoder;


    //员工注册账号
    @Override
    public Result register(CommonUser commonUser) {
        System.out.println("register传的值是："+commonUser);
        if (commonUser!=null){
            String phone = commonUser.getPhone();
            String code = commonUser.getCode();
            ValueOperations ops = redisTemplate.opsForValue();
            String codeInRedis = String.valueOf(ops.get(phone));

            System.out.println("code是："+code);
            System.out.println("codeInRedis是："+codeInRedis);

            if (codeInRedis == null){
                return new Result(Code.CODE_EXPIRED,"验证码已过期，请重新获取！");
            }

            if (!code.equals(codeInRedis)){
                return new Result(Code.CODE_ERR,"验证码错误！");
            }
            //BCryptPasswordEncoder是Spring Security提供的一个用于密码加密和验证的类。
            // 使用BCrypt算法来对密码进行哈希加密，是一种安全可靠的加密算法，常用于存储用户密码或敏感信息
//            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//            String encodedPassword = encoder.encode(需要加密的密码);
            String username = commonUser.getUsername();
            String passwordEncode = encoder.encode(commonUser.getPassword());
            System.out.println("passwordEncode加密成功了没"+passwordEncode);
            LambdaQueryWrapper<CommonUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CommonUser::getUsername,username);
            CommonUser commonUserQuery = commonUserMapper.selectOne(queryWrapper);
            if (commonUserQuery!=null){
                return new Result(Code.REGISTER_ERR,"该用户名已存在！");
            }
            commonUser.setStatus("正常");
            commonUser.setPassword(passwordEncode);
            commonUserMapper.insert(commonUser);
            //注册成功后删除redis中的验证码
            redisTemplate.delete(phone);
            return new Result(Code.REGISTER_OK,"注册成功");
        }else {
            return new Result(Code.REGISTER_ERR,"请填写完整的注册信息！");
        }
    }


    //普通员工登录
    @Override
    public Result employeeLogin(CommonUser commonUser) {
        //1、将页面提交的密码进行MD5加密处理
        String password=commonUser.getPassword();
//        password= DigestUtils.md5DigestAsHex(password.getBytes()).trim();

        //2、根据页面提交的用户名查询管理员数据库
        LambdaQueryWrapper<CommonUser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(CommonUser::getUsername,commonUser.getUsername());
        CommonUser commonUserQuery = commonUserMapper.selectOne(queryWrapper);


        //3、如果没有查询到则返回登录失败结果
        if (commonUserQuery == null){
            return new Result(Code.LOGIN_ERR, MessageConstant.LOGIN_ERR_PASS);
        }
        //4、密码对比，如果不一致返回登录失败结果
        if (!password.equals(commonUserQuery.getPassword())){
            return new Result(Code.LOGIN_ERR,MessageConstant.LOGIN_ERR_PASS);
        }

        //5、如果账号状态为”禁用“，则返回登录失败
        if (commonUserQuery.getStatus().equals("禁用")){
            return new Result(Code.LOGIN_ERR,MessageConstant.LOGIN_ERR_STATUS);

        }
        String phone = commonUserQuery.getPhone();
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getPhone,phone);
        Employee employee = employeeMapper.selectOne(lambdaQueryWrapper);
        System.out.println("登陆的employee是："+employee);

        //6、入职登记待审核中，返回登录失败
        if (employee!=null){
            if (employee.getStatus().equals("待审核")){
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                System.out.println("获取到request.getSession().getAttribute了吗"+request.getSession().getAttribute("employee"));
                request.getSession().removeAttribute("employee");//尝试登录失败，清空重复登录验证session
                System.out.println("清除掉request.getSession().getAttribute了吗"+request.getSession().getAttribute("employee"));
                return new Result(Code.LOGIN_ERR,MessageConstant.LOGIN_ERR_AUDIT);
            }
        }
        return new Result(Code.LOGIN_OK,commonUserQuery, MessageConstant.LOGIN_OK);
    }


   //通过手机号查询员工表中的员工
    @Override
    public Result selectByPhone(String phone) {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getPhone,phone);
        Employee employee = employeeMapper.selectOne(queryWrapper);
        System.out.println("员工的phone是："+phone);
        if (employee != null) {
            System.out.println("employee现在的状态是：" + employee.getStatus());
        } else {
            System.out.println("没有这个员工");
        }

        if (employee!=null && !employee.getStatus().equals("待审核")){//判断employee对象的状态不等于"待审核"
            return new Result(Code.SELECT_OK,true);
        }else {
            return new Result(Code.SELECT_ERR,"请先填写入职申请！");
        }
    }


   //员工入职前信息填写提交
    @Override
    public void addUser(Employee employee, HttpServletRequest request) {

        String phone = employee.getPhone();
        String email = employee.getEmail();

        LambdaQueryWrapper<Employee> queryWrapperEmail = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Employee> queryWrapperPhone = new LambdaQueryWrapper<>();

        queryWrapperPhone.eq(Employee::getPhone,phone);
        queryWrapperEmail.eq(Employee::getEmail,email);

        Employee employeeQueryByPhone = employeeMapper.selectOne(queryWrapperPhone);
        Employee employeeQueryByEmail = employeeMapper.selectOne(queryWrapperEmail);

        if (employeeQueryByPhone!=null){
            throw new BusinessException(Code.SAVE_ERR,"该手机号的用户已存在！");
        }

        if (employeeQueryByEmail!=null){
            throw new BusinessException(Code.SAVE_ERR,"该邮箱的用户已存在！");
        }
        employee.setStatus("待审核");
        employee.setPositionId(Long.valueOf(5));//默认员工
        //入职之后才有机会升值
        Integer a = employeeMapper.insert(employee);
        System.out.println("入职信息填写成功了吗："+a);
        if(a!=null){
            request.getSession().removeAttribute("employee");//退出登录
            System.out.println("普通员工的Session清空了？");
            System.out.println("退出登录成功了吗");
        }
    }


    //注册时判断员工账号是否已存在
    @Override
    public CommonUser selectOneByPhone(String phone) {
        LambdaQueryWrapper<CommonUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommonUser::getPhone,phone);
        CommonUser commonUser = commonUserMapper.selectOne(queryWrapper);

        CommonUser result = commonUser != null ? commonUser : new CommonUser();

        return result;
    }


    //定时任务判断该员工账号是否可用
    @Override
    public Result judgeStatus(Integer userId) {
        CommonUser commonUser = commonUserMapper.selectById(userId);
        System.out.println("当前用户登陆的用户是："+commonUser);
        if (commonUser!=null){
            String status = commonUser.getStatus();
            if(status.equals("禁用")){
                return new Result(Code.USER_RESIGN,"您已离职，账号无法使用！");
            }else {
                return new Result(Code.SELECT_OK,"账号状态良好!");
            }
        }else {
            return new Result(Code.SELECT_ERR,"账号已删除！");
        }
    }


    //根据用户名查找用户
    @Override
    public Result selectUsername(String username) {
        LambdaQueryWrapper<CommonUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommonUser::getUsername,username);
        CommonUser commonUser = commonUserMapper.selectOne(queryWrapper);
        if (commonUser!=null){
            return new Result(Code.USER_EXISTS,"该用户名已存在！");
        }
        return new Result(Code.USER_NOT_EXISTS,"该用户名不存在！");
    }
}
